import json
import os
import sys
import time

import acm
from django.core.management import BaseCommand, call_command

ENDPOINT = os.getenv("ACM_ENDPOINT")
NAMESPACE = os.getenv("ACM_NAMESPACE")
AK = os.getenv("ACM_AK")
SK = os.getenv("ACM_SK")
DATA_ID = os.getenv("ACM_DATA_ID")
GROUP = os.getenv("ACM_GROUP")
SERVER_URL_DATA_ID = os.getenv("ACM_SERVER_REGISTRY_DATA_ID")
SERVER_URL_GROUP = os.getenv("ACM_SERVER_REGISTRY_GROUP")
SELF_URL = os.getenv("SELF_URL", "")


class Command(BaseCommand):
    help = "acm config"
    c = acm.ACMClient(ENDPOINT, NAMESPACE, AK, SK)

    def _config_cb(self, args):
        data = args.get("raw_content", "{}")
        data = json.loads(data)
        for item in data:
            call_command("constance", "set", item.get("key"), item.get("value"))
        print(data)
        sys.stdout.flush()

    def _server_url_cb(self, args):
        data = args.get("raw_content", "")
        print(data)
        sys.stdout.flush()

    def _add_settings_watcher(self):
        self.c.add_watcher(DATA_ID, GROUP, self._config_cb)

    def _add_server_url_watcher(self):
        self.c.add_watcher("service.django-example.url", GROUP, self._server_url_cb)

    def _register_server_url(self):
        self.c.publish(SERVER_URL_DATA_ID, SERVER_URL_GROUP, SELF_URL, 60)

    def handle(self, *args, **options):
        if DATA_ID != "":
            self._add_settings_watcher()
        if SERVER_URL_DATA_ID != "":
            self._register_server_url()
        # self._add_server_url_watcher()
        while True:
            time.sleep(60)
